' DEMO for the "Passed Arrays" bug
' This DEMO works with MMBasic V5.0(.0) (the first one) perfektly!
'
' With MMBasic 5.04.5:
' this DEMO works after EDIT + RUN (F2 in the editor)
'
' BUT it crashes afer a second RUN (from the prompt)
'
' [44] t=arr(leftNIdx):arr(leftNIdx)=arr(rightNIdx):arr(rightNIdx)=t
' Error: String too long
'------------------------------------------------------------------------
'Quicksort for strings (NOT working for MMBasic V5.04,05) using recursion
's. https://rosettacode.org/wiki/Sorting_algorithms/Quicksort
'

Option base 0
Dim integer max = 1000
Dim string q(max) length 20, qo

For n = 0 To max
   q(n)=Str$(Rnd()*10000,6)
   Print n,q(n)
   Next

   Timer= 0
   Quicksort q(), 0, max
   tx= Timer/1000

   qo=""
   For n = 0 To max
     Print "#"n,q(n)
     If q(n)<qo Then Print" error":End
     qo=q(n)
   Next
   Print
   Print tx "sec"
End

' Quicksort
Sub quicksort (arr() As string, leftN As INTEGER, rightN As integer)
    Local pivot As integer, leftNIdx As INTEGER, rightNIdx As INTEGER
    Local t As string
    leftNIdx = leftN
    rightNIdx = rightN
    If (rightN - leftN) > 0 Then
        pivot = (leftN + rightN) / 2
        Do While (leftNIdx <= pivot) And (rightNIdx >= pivot)
            Do While (arr(leftNIdx) < arr(pivot)) And (leftNIdx <= pivot)
                leftNIdx = leftNIdx + 1
            Loop
            Do While (arr(rightNIdx) > arr(pivot)) And (rightNIdx >= pivot)
                rightNIdx = rightNIdx - 1
            Loop
            t=arr(leftNIdx):arr(leftNIdx)=arr(rightNIdx):arr(rightNIdx)=t
            leftNIdx = leftNIdx + 1
            rightNIdx = rightNIdx - 1
            If (leftNIdx - 1) = pivot Then
                rightNIdx = rightNIdx + 1
                pivot = rightNIdx
            ElseIf (rightNIdx + 1) = pivot Then
                leftNIdx = leftNIdx - 1
                pivot = leftNIdx
            End If
        Loop
        quicksort arr(), leftN, pivot - 1
        quicksort arr(), pivot + 1, rightN
    End If
End Sub            